package com.wkh.common.app

import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.asynclayoutinflater.view.AsyncLayoutInflater
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleRegistry
import com.wkh.common.annotation.PrintMethod
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

/**
 * @des: Activity的基类
 * @author: wkh
 * @version: 1.0.0
 * @see {@link }
 */
abstract class BaseActivity(@LayoutRes resId: Int, isReuseView: Boolean = false) :
    AppCompatActivity(),
    CoroutineScope by MainScope() {

    private val resourceId = resId

    private val isReuseView = isReuseView

    lateinit var rootView: View

    private var mLifecycleRegistry: CachedLifecycleRegister? = null

    @PrintMethod
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mLifecycleRegistry = CachedLifecycleRegister(this)

        launch {
            rootView = LayoutHelper.get().asyncGet(resourceId)
            setContentView(rootView)
            onReuseInit()
            initView()
        }
    }

    override fun getLifecycle(): Lifecycle {
        mLifecycleRegistry?.run {
            return this
        }
        return super.getLifecycle()
    }

    abstract fun initView()

    /**
     * 重用view需重写此方法对view进行复位操作，防止脏数据展示
     */
    open fun onReuseInit() {

    }

    override fun onDestroy() {
        super.onDestroy()

        if (isReuseView) {
            LayoutHelper.get().cacheView(resourceId, rootView)
        }
        mLifecycleRegistry?.release()

        //对协程挂起操作进行cancel
        cancel()
    }
}